package com.engine.edcreport.biz.loader.action;

import com.api.formmode.cache.ModeComInfo;
import com.engine.cube.biz.CodeBuilder;
import com.engine.edc.util.DBUtil;
import com.engine.edc.util.EDCUtil;
import com.engine.edc.util.ProgressStatus;
import com.engine.edcreport.biz.loader.DataLoaderAction;
import com.weaver.formmodel.util.DateHelper;
import weaver.formmode.data.ModeDataInterface;
import weaver.formmode.setup.ModeRightInfo;
import weaver.formmode.view.ModeViewLog;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;
import weaver.workflow.workflow.WorkflowBillComInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Deprecated
public class ModeSaveAction extends DataLoaderAction {
    private String valueKey;
    private String dbKey;
    private String formId;
    private String updateSql;
    private String tableName;
    private String modeId;
    private String currentDate;
    private String currentTime;
    private List<String> dbKeys;
    private List<String> ids;

    public ModeSaveAction(String modeId, String valueKey, String dbKey){
        this.modeId = modeId;
        this.valueKey = valueKey;
        this.dbKey = dbKey;
        this.formId = new ModeComInfo().getFormId(modeId);
        this.tableName = new WorkflowBillComInfo().getTablename(this.formId);
        this.updateSql = " update "+this.tableName+" set formModeId = ?, modeDataCreater = 1, modeDataCreaterType = 0," +
                "modeDataCreateDate = ?, modeDataCreateTime = ? where "+this.dbKey+" in ";
        this.ids = new ArrayList<>();
    }


    @Override
    public void run() {
        if(EDCUtil.isNotEmpty(modeId)) {
            this.currentDate = DateHelper.getCurrentDate();
            this.currentTime = DateHelper.getCurrentTime();
            this.dbKeys = this.getDataList().stream().map(d-> Util.null2String(d.get(this.valueKey))).collect(Collectors.toList());
            this.updateSystemField();
            this.doModeAction();
            ProgressStatus.progress(this.getUuid(),"dataLoader", this.getProgress() + this.getSize());
        }
    }

    @Override
    public void writeLog() {

    }

    private void doModeAction() {
        int modeId = Util.getIntValue(this.modeId);
        int formId = Util.getIntValue(this.formId);
        int userId = 1;
        int userLan = 7;
        Integer createExpandId = DBUtil.queryForObject("select id from mode_pageexpand where issystem=1 and issystemflag = ? and modeid = ?",
                Integer.class,1, modeId);
        Integer upateExpandId = DBUtil.queryForObject("select id from mode_pageexpand where issystem=1 and issystemflag = ? and modeid = ?",
                Integer.class,2, modeId);
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        ModeViewLog modeViewLog = new ModeViewLog();
        final int[] progress = {this.getProgress()};
        this.ids.forEach(id->{
            boolean isCreate = true;
            int intId = Util.getIntValue(id);
            if (isCreate) {
                modeRightInfo.setNewRight(true);
                modeRightInfo.editModeDataShare(userId, modeId, intId);//新建的时候添加共享

                CodeBuilder builder = new CodeBuilder(modeId);
                builder.setLanguage(userLan);
                builder.getModeCodeStr(formId, intId);//生成编号
            } else {
                modeRightInfo.rebuildModeDataShareByEdit(userId, modeId, intId);//编辑时重新生成默认共享
            }
            modeRightInfo.addDocShare(userId, modeId, intId);//给文档赋权

            int operateType = isCreate ? 1 : 2;// 1:新建 2:编辑

            if (modeId > 0) {//支持页面扩展
                //执行DML接口
                ModeDataInterface modeDataInterface = new ModeDataInterface();
                modeDataInterface.setFormid(formId);
                modeDataInterface.setBillid(id);
                modeDataInterface.setPageexpandid(isCreate?createExpandId:upateExpandId);
                modeDataInterface.setModeid(modeId);
                modeDataInterface.setUser(new User(1));
                modeDataInterface.execute();
            }

            String operateDesc = isCreate ? SystemEnv.getHtmlLabelName(1421, userLan) :
                    SystemEnv.getHtmlLabelName(33797, userLan);//新增、修改
            int htmllabelindex = 0;//#887673
            htmllabelindex = isCreate ? 1421 : 33797;
            modeViewLog.resetParameter();
            modeViewLog.setClientaddress("");
            modeViewLog.setModeid(modeId);
            modeViewLog.setOperatedesc(operateDesc);
            modeViewLog.setHtmllabelindex(htmllabelindex);
            modeViewLog.setOperatetype(String.valueOf(operateType));
            modeViewLog.setOperateuserid(userId);
            modeViewLog.setRelatedid(intId);
            try {
               modeViewLog.setSysLogInfo();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(progress[0] < this.getProgress() + this.getSize())
                ProgressStatus.progress(this.getUuid(),"dataLoader", progress[0]++);
        });
    }

    private void updateSystemField() {
        int size = dbKeys.size();
        for (int i = 0; i < dbKeys.size();) {
            int next = i+50;
            this.updateSystemField(dbKeys.subList(i, Math.min(next, size)));
            i = next;
        }
    }

    private void updateSystemField(List<String> subList) {
        String sqlWhere = subList.stream().map(d->"?").collect(Collectors.joining(","));
        String sql = this.updateSql + "("+sqlWhere+")";
        List<String> params = new ArrayList<>();
        params.add(this.modeId);
        params.add(this.currentDate);
        params.add(this.currentTime);
        params.addAll(subList);
        DBUtil.update(sql, params.toArray());
        this.ids.addAll(DBUtil.queryForList("select id from "+this.tableName+" where "+this.dbKey+" in ("+sqlWhere+")", String.class, subList.toArray()));
    }
}
